package com.zjtobacco.controller;

import java.io.Serializable;
import java.util.List;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zjtobacco.domain.BaseModel;
import com.zjtobacco.domain.Warehouse;
import com.zjtobacco.service.BaseService;

public abstract class BaseController<T extends BaseModel, ID extends Serializable> {

	abstract BaseService<T, ID> getBaseService();

	@RequestMapping("list")
	public ModelAndView list(T t) {
		List<T> tList = null;
		ModelAndView modelAndView = new ModelAndView();
		try {
			tList = getBaseService().list(t);
		} catch (Exception e) {
			e.printStackTrace();
		}

		modelAndView.addObject("resultList", tList);
		return modelAndView;
	}

	@RequestMapping("save")
	public String save(T t) {
		try {
			if (t.getId() == null) {
				this.getBaseService().save(t);
			} else {
				this.getBaseService().update(t);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:./list";
	}

	@RequestMapping("edit")
	public ModelAndView addOrUpdate(T t) {
		
		ModelAndView modelAndView = new ModelAndView();
		if (t == null) {
			return modelAndView;
		}

		try {
			T tInDb = this.getBaseService().get((ID) (t.getId()));

			modelAndView.addObject("currentObj", tInDb);
			addDataForEditView(modelAndView);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return modelAndView;
	}

	public abstract void addDataForEditView(ModelAndView modelAndView) throws Exception;

	@RequestMapping("delete")
	public String delete(T t) {
		try {
			this.getBaseService().delete((ID) (t.getId()));

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:./list";
	}
}
